<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人订单列表</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!--引入图标库-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
    <link href="https://cdn.jsdelivr.net/npm/element-ui/lib/theme-chalk/index.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/layui/dist/css/layui.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/element-ui/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/layui/dist/layui.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/file-saver/dist/FileSaver.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/axios.min.js"></script>
    <script src="js/data.js"></script>
    <script src="js/pulblicfuntion.js"></script>
</head>
<body>
<!--container mt-5-->
<div id="app" class="">

    <!--头部-->
    <nav class="navbar">
        <div class="nav-container" style="width: 100%;position: relative;">
            <a href="book.html" class="brand"><i class="bi bi-house-door"></i> 首页</a>
            <ul class="nav-links">
                <li><a href="dingdan.html"><i class="bi bi-clipboard-data"></i> 我的订单</a></li>
                <li><a href="gouwuche.html"><i class="bi bi-cart"></i> 我的购物车</a></li>
                <li><a href="myborrow.html"><i class="bi bi-journal-check"></i> 借书记录</a></li>
                <li><a href="#"><i class="bi bi-heart"></i> 我的收藏</a></li>
                <li><a href="gonggao.html"><i class="bi bi-megaphone"></i> 系统公告(5)</a></li>
                <li><a href="wenda.html"><i class="bi bi-chat-text"></i> 问答(5)</a></li>
                <li style="margin-left: 100px;">
                    <img @click="show_alter_info" style="width: 32px;cursor: pointer;" :src="user.profile" alt="">
                </li>
                <li><a href="zhuye.html"><i class="bi bi-person"></i> 主页</a></li>
                <li @click="logout"><i class="bi bi-box-arrow-right"></i> 退出登录</li>
            </ul>
        </div>
    </nav>
    <!--头部end-->

    <div class="row" style="margin-top: 25px;">
        <div class="col-md-4">
            <el-card>
                <div slot="header">
                    <h2>数据统计</h2>
                </div>
                <div class="stat-card">
                    <i class="el-icon-s-order"></i>
                    <div class="stat-info">
                        <span>交易数</span>
                        <strong>{{ totalOrders }}</strong>
                    </div>
                </div>
                <div class="stat-card">
                    <i class="el-icon-s-management"></i>
                    <div class="stat-info">
                        <span>书本量</span>
                        <strong>{{ totalBooks }}</strong>
                    </div>
                </div>
                <div class="stat-card">
                    <i class="el-icon-s-finance"></i>
                    <div class="stat-info">
                        <span>交易总额</span>
                        <strong>{{ totalAmount }}</strong>
                    </div>
                </div>
                <div id="orderChart" style="width: 100%; height: 400px;"></div>
            </el-card>
        </div>
        <div class="col-md-8">
            <el-card>
                <div slot="header">
                    <h2>个人订单列表</h2>
                    <el-input v-model="search" placeholder="搜索订单" class="mb-3" @input="filterOrders"></el-input>
                    <el-button type="primary" @click="exportToExcel">导出为Excel</el-button>
                    <el-button type="primary" @click="exportToPDF">导出为PDF</el-button>
                    <el-button type="primary" @click="exportToCSV">导出为CSV</el-button>
                </div>
                <el-table :data="paginatedOrders" style="width: 100%">
                    <el-table-column prop="id" label="订单编号" width="120"></el-table-column>
                    <el-table-column prop="bookid" label="图书编号" width="120"></el-table-column>
                    <el-table-column prop="time" label="下单时间" width="180"></el-table-column>
                    <el-table-column prop="num" label="数量" width="100"></el-table-column>
                    <el-table-column prop="price" label="单价" width="100"></el-table-column>
                    <el-table-column prop="totalprice" label="总价" width="100"></el-table-column>
                </el-table>
                <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="filteredOrders.length"
                        :page-size="pageSize"
                        @current-change="handlePageChange">
                </el-pagination>
            </el-card>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                orders: this.generateOrders(),
                search: '',
                filteredOrders: [],
                pageSize: 10,
                currentPage: 1,
                user:{},
            };
        },
        computed: {
            totalOrders() {
                return this.orders.length;
            },
            totalBooks() {
                return this.orders.reduce((sum, order) => sum + order.num, 0);
            },
            totalAmount() {
                return this.orders.reduce((sum, order) => sum + order.totalprice, 0);
            },
            paginatedOrders() {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = start + this.pageSize;
                return this.filteredOrders.slice(start, end);
            }
        },
        mounted() {
            this.filteredOrders = this.orders;
            this.initChart();
        },
        created() {
            // 读取登录用户信息
            axios.get(urlluodeng + '/user/getLoginUser').then((response) => {
                if (!response.data.result) {
                    alert(response.data.msg);
                    window.location.href = 'login.html';
                } else {
                    this.user = response.data.userData;
                    //用户信息获取成功后，获取数据列表
                    /*// 获取公告信息
                    axios.get(urlluodeng + '/gonggao/getgonggaotop4').then((response) => {
                        if (response.data.result) {
                            this.gonggao_list = response.data.data;
                        } else {
                            layer.msg("code:500", {icon: 2, time: 2000});
                        }
                    }).catch((error) => {
                        layer.msg("网络错误，请稍后再试", {icon: 2, time: 2000});
                    })*/

                }
            });
        },
        watch: {
            filteredOrders() {
                this.initChart(); // 当过滤后的订单数据改变时，重新刷新图表
            }
        },
        methods: {
            show_alter_info() {
                showUserAvatar(this.user);
            },
            logout() {
                logout();
            },


            generateOrders() {
                const orders = [];
                const startDate = new Date('2024-07-21');
                const endDate = new Date('2024-07-27');
                const bookIds = ['B001', 'B002', 'B003', 'B004', 'B005', 'B006'];
                const prices = [100, 150, 200, 120, 80, 200];

                for (let i = 1; i <= 20; i++) {
                    const randomDate = new Date(startDate.getTime() + Math.random() * (endDate.getTime() - startDate.getTime()));
                    const bookIndex = Math.floor(Math.random() * bookIds.length);
                    const num = Math.floor(Math.random() * 5) + 1;
                    const price = prices[bookIndex];
                    orders.push({
                        id: i.toString().padStart(3, '0'),
                        bookid: bookIds[bookIndex],
                        time: randomDate.toISOString().split('T')[0] + ' ' + ('0' + randomDate.getHours()).slice(-2) + ':' + ('0' + randomDate.getMinutes()).slice(-2),
                        num: num,
                        price: price,
                        totalprice: num * price
                    });
                }
                return orders;
            },
            filterOrders() {
                this.filteredOrders = this.orders.filter(order => {
                    return Object.values(order).some(value => value.toString().toLowerCase().includes(this.search.toLowerCase()));
                });
            },
            handlePageChange(page) {
                this.currentPage = page;
            },
            exportToExcel() {
                const ws = XLSX.utils.json_to_sheet(this.filteredOrders);
                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, '订单列表');
                XLSX.writeFile(wb, '订单列表.xlsx');
            },
            exportToPDF() {
                // 使用 jsPDF 和 autoTable 生成 PDF
                const { jsPDF } = window.jspdf;

                // 创建一个 jsPDF 实例
                const doc = new jsPDF();

                // 表头
                const columns = [
                    { header: '订单编号', dataKey: 'id' },
                    { header: '图书编号', dataKey: 'bookid' },
                    { header: '下单时间', dataKey: 'time' },
                    { header: '数量', dataKey: 'num' },
                    { header: '单价', dataKey: 'price' },
                    { header: '总价', dataKey: 'totalprice' }
                ];

                // 表数据
                const rows = this.filteredOrders.map(order => {
                    return {
                        id: order.id,
                        bookid: order.bookid,
                        time: order.time,
                        num: order.num,
                        price: order.price,
                        totalprice: order.totalprice
                    };
                });

                // 生成表格
                doc.autoTable({
                    columns: columns,
                    body: rows,
                    styles: { font: 'times' } // 使用 Times 字体
                });

                // 添加统计结果
                const totalOrders = this.totalOrders;
                const totalBooks = this.totalBooks;
                const totalAmount = this.totalAmount;

                doc.autoTable({
                    body: [
                        ['统计结果'],
                        ['总订单数', totalOrders],
                        ['总书本量', totalBooks],
                        ['总交易额', totalAmount]
                    ],
                    startY: doc.autoTable.previous.finalY + 10, // 表格生成后向下偏移
                    theme: 'plain',
                    styles: { font: 'times' } // 使用 Times 字体
                });

                // 获取当前日期
                const currentDate = new Date().toLocaleDateString();

                // 添加发行者和时间
                doc.text(`发行者：罗邓`, 14, doc.autoTable.previous.finalY + 20);
                doc.text(`日期：${currentDate}`, 14, doc.autoTable.previous.finalY + 30);

                // 保存 PDF
                doc.save('订单列表.pdf');
            },
            exportToCSV() {
                const csvContent = this.filteredOrders.map(order => {
                    return Object.values(order).join(',');
                }).join('\n');
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                saveAs(blob, '订单列表.csv');
            },
            initChart() {
                const chart = echarts.init(document.getElementById('orderChart'));

                // 生成最近一周的日期
                const lastWeek = [...Array(7)].map((_, offset) => {
                    const date = new Date('2024-07-21');
                    date.setDate(date.getDate() + offset);
                    return date.toISOString().split('T')[0];
                });

                // 计算每一天的订单数量
                const orderCounts = lastWeek.map(date => {
                    return this.orders.filter(order => order.time.startsWith(date)).length;
                });

                const option = {
                    title: {
                        text: '最近一周的订单量'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    xAxis: {
                        type: 'category',
                        data: lastWeek
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [{
                        data: orderCounts,
                        type: 'line'
                    }]
                };
                chart.setOption(option);
            }
        }
    });
</script>

<style>
    .stat-card {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
    }
    .stat-card i {
        font-size: 36px;
        margin-right: 10px;
    }
    .stat-info {
        display: flex;
        flex-direction: column;
    }
    .stat-info span {
        font-size: 16px;
    }
    .stat-info strong {
        font-size: 24px;
    }
</style>
</body>
</html>
